package com.zys.el.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zys.el.core.service.ICrudService;
import com.zys.el.core.service.impl.CrudServiceImpl;
import com.zys.el.user.dao.ToolsDao;
import com.zys.el.user.po.Tools;
import com.zys.el.user.service.IToolsService;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;

import javax.tools.Tool;
import java.util.List;

@Service
public class ToolsServiceImpl extends CrudServiceImpl<Tools> implements IToolsService {
    /**
     * 根据用户id得到当前用户能看到的工具
     *
     * @param UserId
     * @return
     */
    @Override
    public List<Tools> getToolsByUserId(Long UserId) {
        QueryWrapper<Tools> qw = new QueryWrapper<>();
        qw.eq("authorization_", 1);
        List<Tools> publicToos = this.baseMapper.selectList(qw);

        List<Tools> AuthTools = this.selectLookTools(UserId);

        List<Tools> union = ListUtils.union(publicToos, AuthTools);
        return union;
    }

    /**
     * 查询当前用户被授权工具
     *
     * @param uid
     * @return
     */
    @Override
    public List<Tools> selectLookTools(Long uid) {
        return ((ToolsDao) getBaseMapper()).selectLookTools(uid);
    }

    /**
     * 给uids多个用户授权，修改识别码和增加中间表
     *
     * @param tid
     * @param uids
     * @return
     */
    @Override
    public boolean AuthToUsers(Long tid, List<Long> uids) {
        Tools tool = this.getById(tid);
        if (tool == null) return false;

        tool.setAuthorization(2);
        boolean b = this.saveOrUpdate(tool);
        if (b == false) return false;

        for (Long uid : uids) {
            boolean result = this.insertToolsAndUser(tid, uid);
        }
        return true;
    }

    /**
     * 插入中间表
     *
     * @param toolsId
     * @param userId
     * @return
     */
    @Override
    public boolean insertToolsAndUser(Long toolsId, Long userId) {
        return ((ToolsDao) getBaseMapper()).insertToolsAndUser(toolsId, userId);
    }
}
